<template>
  <ui-page class="home" :enable-refresh="true" @refresh="handlePageRefresh">
    <view class="home__banner">
      <home-banner
          ref="banner"
      ></home-banner>
    </view>
    <view class="home__quota">
      <home-quota :data="countData" :delivery-data="deliveryData"></home-quota>
    </view>

    <view class="home-time">
      <view class="home-time__content">
        {{ translate('home_current_time') }}
        <text class="home-time__zone">
          {{ currentTimeType === '1' ? translate('home_time_riyadh') : translate('home_time_beijing') }}
        </text>
        <view class="home-time__switch" @click="handleUpdateClick()">
          {{ translate('home_switch_time') }}
        </view>
      </view>
    </view>

    <view class="home__car">
      <home-process
          :data="processList"
          :dept-name="deptName"
          :display-flag="displayFlag"
          :display-dot-flag="displayDotFlag"
          :caiwu-data="processFYList"
          :display-fy-flag="displayFYFlag"
          :display-fy-dot-flag="displayFYDotFlag"
          :uncomplete-xt="uncompleteXt"
          :uncomplete-cw="uncompleteCw"
          :expire-data="expireData"
      >
      </home-process>
    </view>

    <view class="home__tips" v-if="!checkFlag">
      <bi-follow-official-account></bi-follow-official-account>
    </view>
  </ui-page>
</template>

<script>
import { mapGetters } from 'vuex'
import HomeBanner from './home-banner.vue'
import HomeQuota from './home-quota.vue'
import { getShareData } from '@/utils/share.js'
import BiFollowOfficialAccount from '@/common/follow-official-account/follow-official-account.vue';
import { getOrderData } from '@/apis/order.js';
import HomeProcess from "./home-process.vue";
import { loadOrderListData } from "../../apis/order";
import storage from '@/utils/storage'
import { getLoginUser } from "../../apis/account";
import { error } from "@huntianning/miniprogram/components/ui-message/ui-message.js";
import { getMenuText } from '@/utils/menu-i18n.js'
// 导入语言文件
import zhLang from '@/utils/zh.js';
import enLang from '@/utils/en.js';
import { updateTabBarLanguage } from '@/utils/tabbar-i18n.js'

export default {
  components: {
    HomeProcess,
    HomeBanner,
    HomeQuota,
    BiFollowOfficialAccount
  },
  watch: {
    $route(to, from) {
      // 当路由发生变化时，触发页面刷新操作
      this.refreshPage();
    }
  },
  data () {
    return {
      currentTimeType: null,
      countData: {},
      expireData: {},
      deliveryData: {},
      checkFlag: true,
      processList: [],
      processFYList: [],
      deptName: null,
      displayFlag: false,
      displayDotFlag: false,
      displayFYFlag: false,
      displayFYDotFlag: false,
      uncompleteXt: 0,
      uncompleteCw: 0,
      currentLocale: 'zh', // 默认语言
      // 语言包
      languages: {
        'zh': zhLang,
        'en': enLang
      },
      menuTexts: {
        home: getMenuText('home'),
        order: getMenuText('order'),
        finance: getMenuText('finance'),
        delivery: getMenuText('delivery'),
        mine: getMenuText('mine')
      }
    }
  },
  computed: {
    ...mapGetters([
      'currentUser'
    ]),
    ...mapGetters(['isLogin'])
  },
  onShow () {
    // 初始化语言
    let savedLanguage = uni.getStorageSync('language') || 'zh';
    const currentTimeType = storage.get('CURRENT_TIME_TYPE');
    savedLanguage=(currentTimeType === 1 || currentTimeType === '1') ? 'en' : 'zh';
    // 重新获取时间类型设置，确保从设置页面返回后能正确更新
    this.currentTimeType = storage.get('CURRENT_TIME_TYPE');
    this.currentLocale = savedLanguage;
    if (this.isLogin) {
      this.getCountData()
      this.handleProcessData()
      this.handleProcessFYData()
      this.getUserInfo()
    }
    // 每次显示页面时都强制更新底部页签
    this.$nextTick(() => {
      this.updateLanguage();
    });
  },
  onPullDownRefresh () {
    if (this.$refs.homeCar) {
      this.$refs.homeCar.reload().finally(() => {
        uni.stopPullDownRefresh()
      })
    }
  },
  onLoad () {
    this.updateLanguage()
    uni.getNetworkType({
      success: (res) => {
        if (res.networkType === 'none') {
          error('无网络连接，请检查网络');
        } else if (res.weakNet === true) {
          error('网络连接比较弱，请检查网络');
        }
      }
    });

    // 初始化语言
    let savedLanguage = uni.getStorageSync('language') || 'zh';
    const currentTimeType = storage.get('CURRENT_TIME_TYPE');
    savedLanguage=(currentTimeType === 1 || currentTimeType === '1') ? 'en' : 'zh';
    this.currentLocale = savedLanguage;

    if (this.isLogin) {
      this.currentTimeType = storage.get('CURRENT_TIME_TYPE')
      this.refreshPage();
    } else {
      uni.redirectTo({
        url: '/pages/login/login?returnUrl=' + '\/pages\/home\/home'
      })
    }
  },
  onShareAppMessage () {
    return getShareData()
  },
  methods: {
    // 更新当前语言设置
    updateCurrentLocale() {
      let savedLanguage = uni.getStorageSync('language') || 'zh';
      const currentTimeType = storage.get('CURRENT_TIME_TYPE');
      savedLanguage=(currentTimeType === 1 || currentTimeType === '1') ? 'en' : 'zh';
      this.currentLocale = savedLanguage;
    },

    updateLanguage() {
      this.updateCurrentLocale();
      this.updateTabBarLanguage();
      this.updateMenuTexts();
    },

    updateTabBarLanguage() {
      updateTabBarLanguage()
    },

    updateMenuTexts() {
      this.menuTexts = {
        home: getMenuText('home'),
        order: getMenuText('order'),
        finance: getMenuText('finance'),
        delivery: getMenuText('delivery'),
        mine: getMenuText('mine')
      }
      // 确保底部标签栏也更新
      this.$nextTick(() => {
        updateTabBarLanguage();
      });
    },

    // 翻译函数 - 与 order-delivery 页面保持一致
    translate(key) {
      // 确保使用最新的语言设置
      this.updateCurrentLocale();
      try {
        const langPack = this.languages[this.currentLocale] || this.languages['zh'];
        return langPack[key] || key;
      } catch (e) {
        console.error('Translation error:', e);
        return key;
      }
    },

    refreshPage() {
      this.updateCurrentLocale();
      this.getCountData()
      this.handleProcessData()
      this.handleProcessFYData()
      this.currentTimeType = storage.get('CURRENT_TIME_TYPE')
      this.getUserInfo()

      // 确保语言更新
      this.$nextTick(() => {
        this.updateLanguage();
      });
    },

    getUserInfo() {
      getLoginUser().then(rs => {
        this.deptName = rs.deptName
      })
    },

    handleUpdateClick() {
      const that = this;
      uni.navigateTo({
        url: '/packages/mine/mine-setting/mine-setting-clock?from=1',
        events: {
          // 监听从设置页面返回时触发的事件
          refreshTabBar: function(data) {
            // 更新语言
            that.updateLanguage();
            // 刷新页面数据
            that.refreshPage();
          }
        }
      });
    },

    handleScrollToLower() {
      this.getCountData()
      this.handleProcessData()
      this.handleProcessFYData()
    },

    handlePageRefresh() {
      this.updateCurrentLocale();
      this.getCountData()
      this.handleProcessData()
      this.handleProcessFYData()
      this.getUserInfo()
      this.currentTimeType = storage.get('CURRENT_TIME_TYPE')

      // 确保语言更新
      this.$nextTick(() => {
        this.updateLanguage();
      });
    },

    handleProcessData() {
      let param = {
        orderType: 1,
        orderStatus: 1,
        pageNo: 1,
        pageSize: 10000
      }
      loadOrderListData(param).then((rs) => {
        if (rs && rs.records) {
          let records = rs.records
          if (records.length > 0) {
            this.uncompleteXt = rs.records.length
            if (records.length > 3) {
              this.displayDotFlag = true
            } else {
              this.displayDotFlag = false
            }
            this.displayFlag = true
          } else {
            this.displayFlag = false
            this.displayDotFlag = false
            this.uncompleteXt = 0
          }
          this.processList = records.slice(0, 3)
        } else {
          this.processList = []
          this.uncompleteXt = 0
        }
      })
    },

    handleProcessFYData() {
      let param = {
        orderType: 2,
        orderStatus: 1,
        pageNo: 1,
        pageSize: 10000
      }
      loadOrderListData(param).then((rs) => {
        if (rs && rs.records) {
          let records = rs.records
          if (records.length > 0) {
            this.uncompleteCw = rs.records.length
            if (records.length > 3) {
              this.displayFYDotFlag = true
            } else {
              this.displayFYDotFlag = false
            }
            this.displayFYFlag = true
          } else {
            this.displayFYFlag = false
            this.displayFYDotFlag = false
            this.uncompleteCw = 0
          }
          this.processFYList = records.slice(0, 3)
        } else {
          this.processFYList = []
          this.uncompleteCw = 0
        }
      })
    },

    getCountData() {
      getOrderData().then(rs => {
        this.countData = rs
        this.expireData = rs.expireData
        this.deliveryData = rs.deliveryData
      })
    }
  }
}
</script>

<style lang="less">
.home__banner {
  margin-bottom: 20rpx;
}

.home__quota {
  margin-bottom: 20rpx;
}

.home__tips {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px 16px;
  z-index: 10;
}

.home-time {
  height: 100rpx;
  background-color: white;
  border-radius: 15rpx;
  margin: 15rpx 20rpx;
  box-shadow: 5rpx 5rpx 8rpx #bfbfbf;
}

.home-time__content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  font-weight: bold;
  font-size: 28rpx;
}

.home-time__zone {
  color: #f47554;
  margin: 0 10rpx;
}

.home-time__switch {
  text-align: center;
  width: 140rpx;
  background-color: #409049;
  color: white;
  height: 42rpx;
  border-radius: 15rpx;
  font-size: 25rpx;
  line-height: 42rpx;
}

.home {
  height: 2000rpx;
  margin-top: -200rpx;
}
</style>
